<?php
/**
 * 
 * APP后台公用类
 * @author cls
 *
 * $result = "n";// 服务端返回的结果，Y：成功 N：失败
 * $errorCode = "";// 服务端返回的errorCode，（大部分是空）
 * $errorMsg = "";//服务端返回的errorMsg，
 * $data =  array();//内容
 * $nextStartId = -1;// 分页时使用，-1代表后续无结果
 * $ambulance = "";//"救护车",特殊情况需要更多字段的时候用，非必须
 * 
 */
class BaseAction extends Action{


	/**
	 * 签名过滤
	 */
	public function _initialize(){
		header('Content-Type:application/json; charset=utf-8');
		$this->param = $_REQUEST;
		$params = $this->param;
		$sign = $params['sign'];
		if(isset($params['test'])){

		}else{
			if(isset($params['sign'])){
				//效验时间戳
// 			if((time() - $params['timestamp']) > 600000){
// 				echo $this->err('访问超时！');
// 				exit;
// 			}
				$sysSign = $this->generateSign($params);
				if($sysSign != $sign) {
					echo $this->err('签名错误！');
					exit;
				}
			}else{
				echo $this->err('签名错误！');
				exit;
			}
			//验证session
			if(MODULE_NAME != 'Login' && MODULE_NAME != 'System' && MODULE_NAME != 'Product' &&  MODULE_NAME != 'School' &&  MODULE_NAME != 'Shop'){//过滤无需验证登录的模块
				$userId = $this->param['userId'];
				$sessionId = $this->param['sessionId'];
				$checkResult = $this->checkSession($sessionId,$userId);
				if($checkResult['status'] == 0){
					echo $this->err($checkResult['msg'],"-10000");
					exit;
				}
			}
		}

	}
    
	/**
	 * 失败
	 * @param $errorCode
	 * @param $errorMsg
	 */
	public function err($errorMsg,$errorCode='',$ambulance=''){
		$result = array(
				'result' => 'n',
				'suc' => false,
				'errorCode' => $errorCode,
				'errorMsg' => $errorMsg
		);
		
		if($ambulance!=''){
			$result['ambulance'] = $ambulance;
		}
		return json_encode($result);
	}
	
	/**
	 * 成功
	 * @param $data
	 */
	public function suc($data,$nextStartId){
		if($data == null){
			$data = array();
		}
		if(count($data) == 0 && isset($nextStartId)){//数组形式，如果为空返回[]
			$data = array();
		}elseif (count($data) == 0 && !isset($nextStartId)){//对象形式，如果为空返回{}
			$data = (object)$data;
		}
		$result = array(
				'result' => 'y',
				'suc' => true,
				'data' => $data,
		);
		if($nextStartId != 0){//分页参数
			$result['nextStartId'] = $nextStartId;
		}
		return json_encode($result);
	}
	
	/**
	 * MD5加密签名
	 * Enter description here ...
	 * @param $params
	 * @param $apiKey
	 * @param $msign
	 */
	public function generateSign($params)
	{
	    ksort($params);//所有请求参数按照字母先后顺序排序
	    $key = C('APP_AJAX_REQUEST_SIGN');
	    $timestamp = $params['timestamp'];
	    //把所有参数名和参数值串在一起
	    foreach ($params as $k => $v){
	    	if($k != 'sign'){
	    		$newSign .= $k."=".$v."&";
	    	}
	    }
	    $newSign = substr($newSign,0,strlen($newSign)-1);
	    $newSign .= $key;
	    //使用MD5进行加密，再转化成小写
	    return strtolower((md5($newSign)));
	}	
	
	/**
	 * 判断会话是否存在
	 * 0：请先登录系统 -1：该账号在其他地方登录1：成功
	 */
	private function checkSession($sessionId,$userId){
		$LoginSession = M('LoginSession');
		$where['user_id'] = $userId;
		$result['status'] = 1;
		$result['msg'] = "";
		$info = $LoginSession->where($where)->find();
		if(count($info) == 0){
			$result['status'] = 0;
			$result['msg'] = "请先登录系统!";
		}elseif(time() > $info['overdue_time']){
			$result['status'] = 0;
			$result['msg'] = "请先登录系统!";
		}elseif ($info['session_id'] != $sessionId){
			$result['status'] = 0;
			$result['msg'] = "该账号在其他地方登录";
		}
		return $result;
	}
}